import datetime
import time
from datetime import datetime, timedelta
from flask import render_template, request, jsonify, current_app, session, url_for, redirect, g, abort

from info import constants, db
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from . import admin_blu


@admin_blu.route('/news_category', methods = ["POST", "GET"])
def news_category():
    """新闻分类管理"""
    if request.method == "GET":
        # 获取参数
        categories = Category.query.all()

        # 新闻分类对象遍历到新闻分类字典列表中
        categories_li = []

        for category in categories:
            categories_li.append(category.to_dict())

        # 去除分类为最新的分类
        categories_li.pop(0)

        data = {
            "categories": categories_li
        }

        return render_template('admin/news_type.html', data = data)


    # 如果是post请求，就代表修改或者添加分类

    # 获取参数
    cname = request.json.get('name')
    cid = request.json.get('id')

    if not cname:
        return jsonify(errno = RET.PARAMERR, errmsg = "参数错误")

    # 如果有分类id，就代表是修改
    if cid:
        try:
            cid = int(cid)
            category = Category.query.get(cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.PARAMERR, errmsg = "参数错误")

        if not category:
            return jsonify(errno = RET.NODATA, ermsg= "未查询到分类数据")

        category.name = cname
    # 如果没有cid，就代表是增加分类
    else:
        category = Category()
        category.name = cname
        db.session.add(category)

    return jsonify(errno = RET.OK, errmsg = "OK")

@admin_blu.route('/news_edit_detail', methods = ["POST", "GET"])
def news_edit_detail():
    """新闻板式编辑的跳转"""
    # 如果请求的方式为GET，就做读取操作
    if request.method == "GET":
        # 获取参数
        news_id = request.args.get('news_id')

        # 校验参数
        if not news_id:
            abort(404)

        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)

        # 查询新闻数据
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)

        if not news:
            return render_template('admin/news_edit_detail.html', data = {"errmsg": "没有查询到新闻"})

        # 查询分类的数据
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        categories_li = []
        for category in categories:
            c_dict = category.to_dict()
            c_dict["is_selected"] = False
            if category.id == news.category_id:
                c_dict["is_selected"] = True
            categories_li.append(c_dict)
            # 移除`最新`分类
        categories_li.pop(0)

        data = {
            "news": news.to_dict(),
            "categories": categories_li
        }

        return render_template('admin/news_edit_detail.html', data = data)

    # 如果是POST请求方式，就是对新闻板式的修改

    # 获取参数
    title = request.form.get('title')
    news_id = request.form.get('news_id')
    content = request.form.get('content')
    digest = request.form.get('digest')
    category_id = request.form.get('category_id')
    index_image = request.files.get('index_image')

    # 校验参数
    if not all([title, content, category_id, digest]):
        return jsonify(errno = RET.PARAMERR, errmsg = "参数错误")

    # 获取新闻数据
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = "数据查询失败")

    if not news:
        return jsonify(errno = RET.NODATA, errmsg = "没有查到此新闻")

    # 读取图片
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.PARAMERR, errmsg = "读取图片失败")

        # 上传图片到七牛云
        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno = RET.THIRDERR, errmsg = "上传图片失败")
        # 新闻的索引图片地址是：
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    # 设置新闻的相关信息
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    return jsonify(errno = RET.OK, errmsg = "版式修改成功")


@admin_blu.route('/news_edit')
def news_edit():
    """新闻编辑"""
    page = request.args.get("p", 1)
    keywords = request.args.get("keywords", None)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status == 0]
    # 如果关键字存在，那么就添加关键字搜索
    if keywords:
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters) \
            .order_by(News.create_time.desc()) \
            .paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)

        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())

    context = {"total_page": total_page, "current_page": current_page, "news_list": news_dict_list}

    return render_template('admin/news_edit.html', data=context)



@admin_blu.route('/news_review_action', methods = ["POST"])
def news_review_action():
    """新闻审核详情页的编辑操作"""

    # 获取参数
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 校验参数
    if not all([news_id, action]):
        return jsonify(errno = RET.PARAMERR, errmsg = "参数错误")

    if action not  in ("accept", "reject"):
        return jsonify(errno = RET.PARAMERR, errmsg = "参数错误")

    # 获取新闻数据对象
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno = RET.DBERR, errmsg = "数据查询失败")

    if not news:
        return jsonify(errno = RET.NODATA, errmsg = "没有查询到此新闻")

    # 如果审核通过
    if action == "accept":
        news.status = 0
    # 如果审核不通过
    else:
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno = RET.PARAMERR, errmsg = "请输入拒绝原因")
        news.reason = reason
        news.status = -1

    return jsonify(errno = RET.OK, errmsg = "操作成功")



@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    """新闻审核详情页的显示"""

    # 通过id查询新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    if not news:
        return render_template('admin/news_review_detail.html', data={"errmsg": "未查询到此新闻"})

    # 返回数据
    data = {"news": news.to_dict()}
    return render_template('admin/news_review_detail.html', data=data)




@admin_blu.route('/news_review')
def news_review():
    """新闻审核界面的展示"""

    # 获取参数
    page = request.args.get('p', 1)
    keywords = request.args.get('keywords', None)

    # 校验参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    # 初始化新闻模型对象
    news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status != 0]
    # 如果关键字存在，那么就添加关键字搜索
    if keywords:
        filters.append(News.title.contains(keywords))

    # 从数据库中读取新闻
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, constants.ADMIN_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)

    # 遍历新闻模型对象到新闻字典列表中
    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "news_list": news_dict_li
    }

    return render_template('admin/news_review.html', data = data)


@admin_blu.route('/user_list')
@user_login_data
def user_list():
    """后台管理系统的用户列表"""
    # 获取参数
    page = request.args.get('p', 1)

    # 校验参数
    try:
        page= int(page)
    except Exception as e:
        page = 1

    # 设置默认变量
    users = []
    total_page = 1
    current_page = 1

    # 从User表中读取用户信息
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)
        users = paginate.items  # 用户的信息
        current_page = paginate.page  # 总页数
        total_page = paginate.pages  # 当前页数
    except Exception as e:
        current_app.logger.error(e)

    users_list = []
    # 遍历用户信息对象列表到字典列表中
    for user in users:
        users_list.append(user.to_admin_dict())

    data = {
        "current_page": current_page,
        "total_page": total_page,
        "users":users_list
    }
    return render_template('admin/user_list.html', data = data)



@admin_blu.route('/user_count')
def user_count():

    # 总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 月新增数
    mon_count = 0
    # t的值是：time.struct_time(tm_year=2018, tm_mon=10, tm_mday=28, tm_hour=15, tm_min=44, tm_sec=49, tm_wday=6, tm_yday=301, tm_isdst=0)
    t = time.localtime()
    # 月份开始的时间 2018-10-01 00:00:00
    begin_mon_date = datetime.strptime(('%d-%02d-01' % (t.tm_year, t.tm_mon)), "%Y-%m-%d")
    try:
        mon_count = User.query.filter(User.is_admin==False, User.create_time > begin_mon_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 日新增数
    day_count = 0
    # 当天开始的时间 2018-10-28 00:00:00
    begin_day_date = datetime.strptime(('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)), "%Y-%m-%d")
    try:
        day_count = User.query.filter(User.is_admin==False, User.create_time > begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 拆线图数据

    active_time = []
    active_count = []

    # 取到今天的时间字符串
    today_date_str = ('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday))
    # 转成时间对象
    today_date = datetime.strptime(today_date_str, "%Y-%m-%d")

    for i in range(0, 31):
        # 取到某一天的0点0分
        begin_date = today_date - timedelta(days=i)
        # 取到下一天的0点0分
        end_date = today_date - timedelta(days=(i - 1))
        count = User.query.filter(User.is_admin == False, User.last_login >= begin_date, User.last_login < end_date).count()
        active_count.append(count)
        active_time.append(begin_date.strftime('%Y-%m-%d'))

    # User.query.filter(User.is_admin == False, User.last_login >= 今天0点0分, User.last_login < 今天24点).count()

    # 反转，让最近的一天显示在最后
    active_time.reverse()
    active_count.reverse()

    data = {
        "total_count": total_count,
        "mon_count": mon_count,
        "day_count": day_count,
        "active_time": active_time,
        "active_count": active_count
    }

    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/index')
@user_login_data
def index():
    """后台管理的主页"""
    user = g.user
    return render_template('admin/index.html', user = user.to_dict())


@admin_blu.route('/login', methods = ["POST", "GET"])
def login():
    """后台登录界面"""

    # 如果请求方式为GET， 就返回登录界面
    if request.method == "GET":
        # 判断是否有管理员账号登录，如果有登陆直接重定向到管理后台主页
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template('admin/login.html')

    # 如果请求方式为POST 就做登录操作
    # 取到登陆的参数
    username = request.form.get('username')
    password = request.form.get('password')

    # 校验参数
    if not all([username, password]):
        return render_template('admin/login.html', errmsg = "参数错误")

    # 查询当前用户
    try:
        user = User.query.filter(User.mobile == username, User.is_admin == True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg = "用户信息查询失败")

    # 如果用户不存在
    if not user:
        return render_template('admin/login.html', errmsg = "没有此用户")

    # 校验密码
    if not user.check_password(password):
        return render_template('admin/login.html', errmsg = "用户名或密码错误")

    # 保存用户的登录信息
    session["user_id"] = user.id
    session["mobile"] = user.mobile
    session["nick_name"] = user.nick_name
    session["is_admin"] = user.is_admin

    # 跳转到后台管理页面
    return redirect(url_for('admin.index'))

